import { login,getUserInfo,logout } from '@/assets/server/testApi'

const state = {
  token: localStorage.getItem('token'),
  name: '',
  avatar: '',
  content: ''
}

const mutations = {
  SET_TOKEN: (state:any, token:string) => {
    state.token = token
  },
  SET_NAME: (state:any, name:string) => {
    state.name = name
  },
  SET_AVATAR: (state:any, avatar:string) => {
    state.avatar = avatar
  },
  SET_CONTENT: (state:any, content:string) => {
    state.content = content
  }
}

const actions = {
  // 登录
  login ({
    commit
  }: any, formObj: { username: string; password: string }) {
    const {
      username,
      password
    } = formObj
    return new Promise((resolve, reject) => {
      login({
        username,
        password
      })
        .then((res: any) => {
          // console.log(res)
          const {
            token
          } = res.data
          localStorage.setItem('token', token)
          localStorage.setItem('username', username)
          commit('SET_TOKEN', token)
          resolve()
        })
        .catch((error: object) => {
          reject(error)
        })
    })
  },
  getUserInfo ({ commit }:any) {
    return new Promise((resolve, reject) => {
      getUserInfo().then((response: any) => {
        const { data } = response
        const { name, avatar, content } = data.info
        if (!data) {
          reject('验证失败，请重新登录.')
        }
        // commit('SET_NAME', name)
        commit('SET_NAME', localStorage.getItem('username'))
        commit('SET_AVATAR', avatar)
        commit('SET_CONTENT', content)
        resolve(data)
      }).catch((error: any) => {
        reject(error)
      })
    })
  },
  // 退出登录
  logout ({
    commit,
    state
  }:any) {
    return new Promise((resolve, reject) => {
      logout({
        token: state.token
      }).then(() => {
        commit('SET_TOKEN', '')
        localStorage.removeItem('token')
        resolve()
      }).catch((error: any) => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
